import { useAtomValue } from "jotai";
import { useState, type ReactNode } from "react";
import { Switch, Form, Button, InputNumber, Spin, Radio, Input } from "antd";
import ThermometerIcon from "@/assets/images/thermometer.png?jsx";
import WaterIcon from "@/assets/images/water.png?jsx";
import PressureGaugeIcon from "@/assets/images/pressure-gauge.png?jsx";
import ClockIcon from "@/assets/images/clock-2.png?jsx";
import SaveIcon from "@/assets/images/diskette.png?jsx";
import FullSizeModal from "../FullSizeModal";
import useOnUpdated from "@/lib/hooks/useOnUpdated";
import useFetch from "@/lib/hooks/useFetch";
import { getDeviceConstant, updateDeviceConstant } from "@/lib/api/device";
import { tokenAtom } from "@/store/user";
import type { IDeviceConstant, IDeviceStatus } from "@/lib/types";
import { useMessage } from "@/providers/AntdMessageProvider";

type ConstantSettingDialogProps = {
  device: IDeviceStatus;
  visible: boolean;
  onClose: () => void;
};

const initialData: Partial<IDeviceConstant> = {
  hRateValue: undefined,
  hIsRate: "0",
  hSv: undefined,
  isH: "0",
  pRateValue: undefined,
  pUnit: 1,
  pIsRate: "0",
  pSv: undefined,
  isP: "0",
  tRateValue: undefined,
  tIsRate: "0",
  tSv: undefined,
  isT: "0",
  sv1: undefined,
  isSv1: "0",
  sv2: undefined,
  isSv2: "0",
  sv3: undefined,
  isSv3: "0",
  sv4: undefined,
  isSv4: "0",
  isTime: "0",
  limitTime: undefined,
  limitTimeHour: undefined,
  limitTimeMinute: undefined,
  limitTimeSecond: undefined,
  isLimitWarning: "0",
  isMeasureWarning: "0",
  hWarningLimitLower: 0,
  hWarningLimitUpper: 0,
  pWarningLimitLower: 0,
  pWarningLimitUpper: 0,
  tWarningLimitLower: 0,
  tWarningLimitUpper: 0,
};

export default function ConstantSettingDialog(
  props: ConstantSettingDialogProps,
) {
  const { device, visible, onClose } = props;
  const [formData, setFormData] = useState({ ...initialData });

  const token = useAtomValue(tokenAtom);
  const message = useMessage();

  const { isLoading, refetch: loadDeviceConstant } = useFetch({
    fetchFn: (id: number) =>
      getDeviceConstant(id, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        return res.data;
      }),
    onSuccess(data) {
      const newData: Partial<IDeviceConstant> = {};
      for (const k in formData) {
        const key = k as keyof typeof formData;
        newData[key] = data[key] as any;
      }
      setFormData(newData);
    },
  });

  const { isLoading: isSaving, refetch: saveDeviceConstant } = useFetch({
    fetchFn: (data: Partial<IDeviceConstant>) =>
      updateDeviceConstant(data, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
      }),
    onSuccess() {
      message.success("保存成功！");
      handleClose();
    },
    onError(error) {
      let _message = "保存失败！";
      if ("msg" in error) {
        _message = error.msg;
      } else if ("message" in error) {
        _message = error.message;
      }
      message.error(_message);
    },
  });

  function handleSave() {
    saveDeviceConstant({ deviceId: device.deviceId, ...formData });
  }

  function handleClose() {
    onClose();
  }

  useOnUpdated(() => {
    if (visible && typeof device.deviceId !== "undefined") {
      loadDeviceConstant(device.deviceId);
    }
  }, [visible, device.deviceId]);

  return (
    <FullSizeModal
      title="定值设置"
      visible={visible}
      onClose={handleClose}
      onClosed={() => setFormData({ ...initialData })}
      fullscreen
    >
      <Form
        className="h-full overflow-auto"
        labelCol={{ span: 8 }}
        labelAlign="left"
        colon={false}
      >
        <Spin spinning={isLoading}>
          <div className="grid grid-cols-2">
            {device.isTemperature === 1 && (
              <Section icon={<ThermometerIcon className="h-6" />} title="温度">
                <SectionLine
                  label="目标值℃"
                  value={formData.tSv}
                  onChange={(v) => setFormData((p) => ({ ...p, tSv: v }))}
                  enable={formData.isT === "1"}
                  onEnableChange={(v) =>
                    setFormData((p) => ({ ...p, isT: v ? "1" : "0" }))
                  }
                />
                <SectionLine
                  label="斜率值 ℃/MIN"
                  value={formData.tRateValue}
                  onChange={(v) =>
                    setFormData((p) => ({ ...p, tRateValue: v }))
                  }
                  enable={formData.tIsRate === "1"}
                  onEnableChange={(v) =>
                    setFormData((p) => ({ ...p, tIsRate: v ? "1" : "0" }))
                  }
                />
              </Section>
            )}
            {/* <Section
                icon={<ThermometerIcon className="h-6" />}
                title="壁面温度"
              >
                <SectionLine
                  label="壁面温度1 ℃"
                  value={formData.sv1}
                  onChange={(v) => setFormData((p) => ({ ...p, sv1: v }))}
                  enable={formData.isSv1 === "1"}
                  onEnableChange={(v) =>
                    setFormData((p) => ({ ...p, isSv1: v ? "1" : "0" }))
                  }
                />
                <SectionLine
                  label="壁面温度2 ℃"
                  value={formData.sv2}
                  onChange={(v) => setFormData((p) => ({ ...p, sv2: v }))}
                  enable={formData.isSv2 === "1"}
                  onEnableChange={(v) =>
                    setFormData((p) => ({ ...p, isSv2: v ? "1" : "0" }))
                  }
                />
                <SectionLine
                  label="壁面温度3 ℃"
                  value={formData.sv3}
                  onChange={(v) => setFormData((p) => ({ ...p, sv3: v }))}
                  enable={formData.isSv3 === "1"}
                  onEnableChange={(v) =>
                    setFormData((p) => ({ ...p, isSv3: v ? "1" : "0" }))
                  }
                />
                <SectionLine
                  label="壁面温度4 ℃"
                  value={formData.sv4}
                  onChange={(v) => setFormData((p) => ({ ...p, sv4: v }))}
                  enable={formData.isSv4 === "1"}
                  onEnableChange={(v) =>
                    setFormData((p) => ({ ...p, isSv4: v ? "1" : "0" }))
                  }
                />
              </Section> */}
            {device.isHumidity === 1 && (
              <Section icon={<WaterIcon className="h-6" />} title="湿度">
                <SectionLine
                  label="目标值 %"
                  value={formData.hSv}
                  onChange={(v) => setFormData((p) => ({ ...p, hSv: v }))}
                  enable={formData.isH === "1"}
                  onEnableChange={(v) =>
                    setFormData((p) => ({ ...p, isH: v ? "1" : "0" }))
                  }
                />
                <SectionLine
                  label="斜率值 %/MIN"
                  value={formData.hRateValue}
                  onChange={(v) =>
                    setFormData((p) => ({ ...p, hRateValue: v }))
                  }
                  enable={formData.hIsRate === "1"}
                  onEnableChange={(v) =>
                    setFormData((p) => ({ ...p, hIsRate: v ? "1" : "0" }))
                  }
                />
              </Section>
            )}
            {device.isPressure === 1 && (
              <Section
                icon={<PressureGaugeIcon className="h-6" />}
                title="压力"
              >
                <Form.Item label="单位">
                  <Radio.Group
                    value={formData.pUnit}
                    onChange={(e) =>
                      setFormData((p) => ({
                        ...p,
                        pUnit: parseInt(e.target.value),
                      }))
                    }
                  >
                    <Radio.Button value={1}>Pa</Radio.Button>
                    <Radio.Button value={1000}>kPa</Radio.Button>
                  </Radio.Group>
                </Form.Item>
                <SectionLine
                  label={`目标值 ${formData.pUnit === 1 ? "" : "k"}Pa`}
                  value={formData.pSv}
                  onChange={(v) => setFormData((p) => ({ ...p, pSv: v }))}
                  enable={formData.isP === "1"}
                  onEnableChange={(v) =>
                    setFormData((p) => ({ ...p, isP: v ? "1" : "0" }))
                  }
                />
                <SectionLine
                  label={`斜率值 ${formData.pUnit === 1 ? "" : "k"}Pa/MIN`}
                  value={formData.pRateValue}
                  onChange={(v) =>
                    setFormData((p) => ({ ...p, pRateValue: v }))
                  }
                  enable={formData.pIsRate === "1"}
                  onEnableChange={(v) =>
                    setFormData((p) => ({ ...p, pIsRate: v ? "1" : "0" }))
                  }
                />
              </Section>
            )}
            <Section icon={<ClockIcon className="h-6" />} title="定值时间设定">
              <SectionLine
                label="限制值 MIN"
                value={formData.limitTime}
                onChange={(v) => setFormData((p) => ({ ...p, limitTime: v }))}
                enable={formData.isTime === "1"}
                onEnableChange={(v) =>
                  setFormData((p) => ({ ...p, isTime: v ? "1" : "0" }))
                }
              />
            </Section>
          </div>
          <div className="grid grid-cols-[repeat(auto-fill,300px)] p-8">
            <div>
              <Form.Item label="控制点报警">
                <Switch
                  value={formData.isLimitWarning === "1"}
                  onChange={(v) =>
                    setFormData((p) => ({
                      ...p,
                      isLimitWarning: v ? "1" : "0",
                    }))
                  }
                />
              </Form.Item>
              <Form.Item label="测量点报警">
                <Switch
                  value={formData.isMeasureWarning === "1"}
                  onChange={(v) =>
                    setFormData((p) => ({
                      ...p,
                      isMeasureWarning: v ? "1" : "0",
                    }))
                  }
                />
              </Form.Item>
            </div>
            {device.isTemperature === 1 && (
              <div>
                <Form.Item label="温度超调下限">
                  <InputNumber
                    value={formData.tWarningLimitLower}
                    onChange={(v) =>
                      setFormData((p) => ({ ...p, tWarningLimitLower: v ?? 0 }))
                    }
                  />
                </Form.Item>
                <Form.Item label="温度超调上限">
                  <InputNumber
                    value={formData.tWarningLimitUpper}
                    onChange={(v) =>
                      setFormData((p) => ({ ...p, tWarningLimitUpper: v ?? 0 }))
                    }
                  />
                </Form.Item>
              </div>
            )}
            {device.isHumidity === 1 && (
              <div>
                <Form.Item label="湿度超调下限">
                  <InputNumber
                    value={formData.hWarningLimitLower}
                    onChange={(v) =>
                      setFormData((p) => ({ ...p, hWarningLimitLower: v ?? 0 }))
                    }
                  />
                </Form.Item>
                <Form.Item label="湿度超调上限">
                  <InputNumber
                    value={formData.hWarningLimitUpper}
                    onChange={(v) =>
                      setFormData((p) => ({ ...p, hWarningLimitUpper: v ?? 0 }))
                    }
                  />
                </Form.Item>
              </div>
            )}
            {device.isPressure === 1 && (
              <div>
                <Form.Item label="压力超调下限">
                  <InputNumber
                    value={formData.pWarningLimitLower}
                    onChange={(v) =>
                      setFormData((p) => ({ ...p, pWarningLimitLower: v ?? 0 }))
                    }
                  />
                </Form.Item>
                <Form.Item label="压力超调上限">
                  <InputNumber
                    value={formData.pWarningLimitUpper}
                    onChange={(v) =>
                      setFormData((p) => ({ ...p, pWarningLimitUpper: v ?? 0 }))
                    }
                  />
                </Form.Item>
              </div>
            )}
          </div>
          <div className="mb-14 text-center">
            <Button
              className="relative w-32"
              loading={isSaving}
              onClick={handleSave}
            >
              <SaveIcon className="absolute left-1 size-4" />
              保存
            </Button>
          </div>
        </Spin>
      </Form>
    </FullSizeModal>
  );
}

type SectionProps = {
  icon: ReactNode;
  title: ReactNode;
  children?: ReactNode;
};
function Section(props: SectionProps) {
  const { icon, title, children } = props;
  return (
    <div className="p-8">
      <div className="mb-2 flex">
        {icon}
        <span className="ml-2 text-lg">{title}</span>
      </div>
      {children}
    </div>
  );
}

type SectionLineProps = {
  label: string;
  value?: number;
  onChange: (value?: number) => void;
  enable: boolean;
  onEnableChange: (enable: boolean) => void;
};
function SectionLine(props: SectionLineProps) {
  const { label, value, enable, onChange, onEnableChange } = props;
  return (
    <div className="[&:not(:first-child)]:mb-4">
      <Form.Item
        label={label}
        style={{ marginBottom: 0, flex: "none", flexBasis: "80%" }}
      >
        <div className="flex items-center gap-x-4">
          <InputNumber
            className="w-full"
            disabled={!enable}
            value={value}
            precision={1}
            onChange={(v) => onChange(v || undefined)}
          />
          <Switch checked={enable} onChange={onEnableChange} />
        </div>
      </Form.Item>
    </div>
  );
}
